import os
import re
from global_variable import logging
from openpyxl import Workbook
from global_variable import Var

var = Var()

title_dic = {}  # 所有topic信息 {topic: path}
hyper_dic = {}  # 所有topic下的链接信息 {topic: {hyper_title: link}}


def get_topic(path):
    """
    获取所有topic路径
    :param path: markdown路径
    :return: 所有topic信息 {topic: path}
    """
    markdown_path = path
    for file in os.listdir():
        if '_bookmap_' in file:
            bookmap_path = markdown_path + '\\' + file

            with open(bookmap_path, 'r', encoding='utf-8') as f:
                line = f.read()
                pattern = r'\[(?P<title>.*?)\]\((?P<path>.*?\.md)\)'
                i_list = re.finditer(pattern=pattern, string=line)

                for i in i_list:
                    title_dic[i.group('title')] = markdown_path + '\\' + i.group('path')
                    logging.info(f'{i.group("title")}: {i.group("path")}')
            break


def get_hyperlink(queue):
    """
    获取所有topic下的链接信息 {topic: {hyper_title: link}}
    :return:
    """
    for faq_markdown_path in title_dic.values():
        try:
            with open(faq_markdown_path, 'r', encoding='utf-8') as f:
                text = f.read()
                pattern = r'\[(?P<hyper_title>.*?)\]\((?P<link>.*?)\)'
                i_list = re.finditer(pattern=pattern, string=text)

                for i in i_list:
                    if i.group('hyper_title') == '':
                        continue
                    if not i.group('link').startswith('http'):
                        if '.md' not in i.group('link') and '#' not in i.group('link'):
                            continue

                    if i.group('link').startswith('figures') or i.group(
                            'link').startswith('public_sys-resources'):
                        continue
                    queue.put(''.join([faq_markdown_path.split("\\")[-1][:-3], i.group('hyper_title'), i.group('link')]))
                    link = i.group('link')
                    if link.startswith('#'):
                        link = faq_markdown_path.split("\\")[-1] + link
                    if hyper_dic.get(faq_markdown_path.split("\\")[-1][:-3]):
                        hyper_dic[faq_markdown_path.split("\\")[-1][:-3]].append((i.group('hyper_title'), link))
                    else:
                        hyper_dic[faq_markdown_path.split("\\")[-1][:-3]] = [(i.group('hyper_title'), link)]
        except FileNotFoundError as e:
            queue.put(f'{faq_markdown_path}文件不存在，原因：{e}')


def write_to_excel():
    """
    将获取到的hyper信息写入导表格中
    :return:
    """
    wb = Workbook()
    ws = wb.active
    ws.append(['Topic', '链接信息', '链接地址'])

    for key, value in hyper_dic.items():
        for v in value:
            ws.append([key, v[0], v[1]])

    wb.save('超链接.xlsx')


def main(md_file_path, queue):
    """
    主函数
    :return:
    """
    markdown_path = md_file_path
    os.chdir(markdown_path)

    get_topic(markdown_path)
    get_hyperlink(queue)
    write_to_excel()
    var.excel_path = markdown_path + r'\超链接.xlsx'
    return var.excel_path


if __name__ == '__main__':
    main()
